<template>
  <router-view />
</template>

<script setup>
import { onMounted } from "vue";
import { session, api } from "src/boot/axios.js";
import { useQuasar, QSpinnerIos } from "quasar";
import { useRouter } from "vue-router";
import notify from "src/utility/notify.js";

const router = useRouter();

onMounted(async () => {
  const $q = useQuasar();
  const nowPath = window.location.hash.split("?")[0].replace("#", "");
  console.log("Quasar instance initialized.");

  $q.loadingBar.setDefaults({ color: "primary" });
  console.log("Loading bar defaults set.");

  $q.loading.setDefaults({
    spinner: QSpinnerIos,
    spinnerSize: 40,
    spinnerColor: "grey-8",
    backgroundColor: "grey-3",
  });
  console.log("Loading defaults set.");

  $q.loading.show();
  if (nowPath.startsWith("/blog")) {
    $q.loading.hide();
    console.log("Loading blog page...");
    return;
  }

  try {
    const accessToken = await session.get("token");
    console.log(
      `Access token retrieved: ${accessToken ? "Exists" : "Not found"}`,
    );

    if (accessToken) {
      api.defaults.headers.common["Authorization"] = `${accessToken}`;
      console.log("Authorization header set.");
    } else {
      if (nowPath !== "/") {
        router.push("/");
      }
      throw new Error("No access token retrieved.");
    }

    const sessionUseInfo = await session.get("userInfo");
    console.log("Session user info retrieved:", sessionUseInfo);

    const userInfo = (await api.get("/user/info")).data;
    console.log("User info retrieved from API:", userInfo);

    if (sessionUseInfo && sessionUseInfo.id !== userInfo.id) {
      await session.clear();
      console.log("Session cleared due to id mismatch.");
    }

    await session.set("userInfo", userInfo);
    console.log("User info stored in session.");

    const redirect_url = await session.get("last_href");
    console.log(`Redirect URL retrieved: ${redirect_url || "None"}`);

    if (redirect_url) {
      await session.remove("last_href");
      console.log("Last href removed from session.");
      notify.info("2秒内重定向到上次访问的页面。");
      setTimeout(() => {
        window.location.href = redirect_url;
        console.log(`Redirecting to last href: ${redirect_url}`);

        $q.loading.hide();
        console.log("Loading stopped after redirect.");
      }, 2000);
    } else {
      console.log("No redirect URL found.");
      console.log("nowPath", nowPath);
      if (nowPath === "/") {
        console.log("Current route is not /chatgpt, redirecting now.");
        router.push("/chatgpt");
      } else {
        console.log("Already on /chatgpt, not redirecting.");
      }
    }
  } catch (e) {
    console.error("An error occurred:", e);
    await session.clear();
    console.log("Loading stopped due to error.");
  } finally {
    $q.loading.hide();
  }
});
</script>
